package com.yixun.qfbao.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yixun.qfbao.request.premises.GetPremisesReqDto;

/**
 * @author zilong.liu
 * @date 2020-8-31
 * 	字段转换工具类。
 */
public class FieldConvertUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(FieldConvertUtil.class);
	
	/**
	 * 把对象中含有null元素或者""元素的list对象转换为长度为0的list
	 * 地址引用无需返回
	 * @param object
	 */
	public static void listContainsNullToListNull(Object object) {
    	Field[] fields = object.getClass().getDeclaredFields();
    	for(int i = 0; i < fields.length; i ++) {
    		fields[i].setAccessible(true);
    		if(fields[i].getType().equals(List.class)) {
    			try {
    				String methodName = fields[i].getName().substring(0, 1).toUpperCase() + fields[i].getName().substring(1);
					Method fieldGetMethod = object.getClass().getMethod("get" + methodName);
					@SuppressWarnings("rawtypes")
					List list = (List) fieldGetMethod.invoke(object);
					if(list != null && (list.contains(null) || list.contains(""))) {
						list = new ArrayList<>();
						Method fieldSetMethod = object.getClass().getMethod("set" + methodName, List.class);
						fieldSetMethod.invoke(object, list);
					}
				} catch (Exception e) {
					LOGGER.error("listContainsNullToListNull error: {}", e);
				} 
    		}
    	}
    }
	
	public static void main(String[] args) {
    	GetPremisesReqDto request = new GetPremisesReqDto();
    	List<Integer> saleStatus = new ArrayList<>();
    	saleStatus.add(1);
    	saleStatus.add(2);
    	saleStatus.add(null);
    	request.setSaleStatus(saleStatus);
    	FieldConvertUtil.listContainsNullToListNull(request);
    	System.out.println(request);
	}
}
